package com.studyroom.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.studyroom.dto.Result;
import com.studyroom.dto.RoomPageDTO;
import com.studyroom.dto.UserDTO;
import com.studyroom.entity.Room;
import com.studyroom.entity.RoomMember;
import com.studyroom.entity.User;
import com.studyroom.mapper.RoomMapper;
import com.studyroom.mapper.RoomMemberMapper;
import com.studyroom.service.RoomService;
import com.studyroom.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

import static com.studyroom.utils.RedisContants.ONLINE_KEY;
import static com.studyroom.utils.RedisContants.TOKEN_KEY;

@Service
public class RoomServiceImpl extends ServiceImpl<RoomMapper, Room> implements RoomService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RoomMemberMapper roomMemberMapper;
    @Override
    public Result getPageByType(RoomPageDTO roomPageDTO) {
        //TODO 从redis查询
        //从数据库查询
        IPage<Room> page=new Page<> (roomPageDTO.getCurrent (),roomPageDTO.getSize ());
        query ().eq ("type",roomPageDTO.getType ()).page (page);
        List<Room> rooms=page.getRecords ();
        for(Room room:rooms){
            //从数据库查询该自习室在线用户
            QueryWrapper roomMemberQueryWrapper=new QueryWrapper ();
            roomMemberQueryWrapper.eq ("room_id",room.getId ());
            List<RoomMember> members=roomMemberMapper.selectList (roomMemberQueryWrapper);
            //从redis验证用户是否在线
            //TODO 繁琐 需要改进
            for(int i= members.size ()-1;i>=0;i--){
                String onlineKey=ONLINE_KEY+members.get (i).getUserId ();
                Long count=stringRedisTemplate.getExpire (onlineKey);
                if(count<1){
                    members.remove (i);
                }
            }
            //将在线用户赋予room
            room.setOnlineNumber (members.size ());
        }
        page.setRecords (rooms);
        return Result.ok (page);
    }

    @Override
    public Result getById(Long id) {
        Room room=query ().eq ("id",id).one ();
        if(room==null){
            return Result.fail ("获取自习室信息失败");
        }
        return Result.ok (room);
    }

    @Override
    public Result add(Room room) {
        UserDTO me=UserHolder.getUser ();
        //判断房间名是否存在
        Room queryRoom=query ().eq ("name",room.getName ()).one ();
        if(queryRoom!=null){
            return Result.fail ("该房间名已被使用");
        }
        //判断该用户是否已创建房间
        QueryWrapper wrapper=new QueryWrapper ();
        wrapper.eq ("user_id",me.getId ());
        Room queryRoom2=query ().eq ("user_id",me.getId ()).one ();
        if(queryRoom2!=null){
            return Result.fail ("你已经创建过一个自习室");
        }
        room.setUserId (me.getId ());
        room.setCreated (LocalDateTime.now ());
        boolean b=save (room);
        if(!b){
            return Result.fail ("未知的错误,创建失败");
        }
        return Result.ok ();
    }

    @Override
    public Result getByUserId() {
        UserDTO me= UserHolder.getUser ();
        //根据用户id从数据查询当前用户的自习室
        Room room=query ().eq ("user_id",me.getId ()).one ();
        if(room==null){
            return Result.fail ("你还没有创建自习室");
        }
        return Result.ok (room);
    }

    @Override
    public Result delById(Long id) {
        Room room=getBaseMapper ().selectById (id);
        if(room.getUserId ()!=UserHolder.getUser ().getId ()){
            return Result.fail ("你没有权限关闭房间");
        }
        boolean b=removeById (id);
        if(!b){
            return Result.fail ("关闭失败");
        }
        return Result.ok ();
    }
}
